C#单例 |
您所在的位置:网站首页 › 饿汉式 懒汉式 › C#单例 |
单例模式: 步骤: 1.定义静态私有对象 2.构造函数私有化 3.定义一个静态的,返回值为该类型的方法,一般以Getinstance/getInit为方法名称 单例模式有懒汉和饿汉,最好使用饿汉 1.饿汉式---先实例化 public class Singleton { private static Singleton _singleton = new Singleton();//1 private Singleton() //2 { } public static Singleton GetInstance() //3 { return _singleton; } }
2.懒汉式---后实例化 using System; namespace 单例懒汉{ public class Singleton { private static Singleton _singleton; //1 private Singleton() // 2 { } public static Singleton GetInstance() 3 { if (_singleton == null) { _singleton = new Singleton(); } return _singleton; } }}
|
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |